#include <iostream>
#include <cstring>
using namespace std;

class MyString
{
    char *data_;
    size_t len_;

public:
    MyString(const char *s = "") : len_(std::strlen(s))
    {
        data_ = new char[len_ + 1];
        std::strcpy(data_, s);
        std::cout << "构造: " << data_ << "\n";
    }

    ~MyString()
    {
        delete[] data_;
    }

    MyString(const MyString &rhs) : len_(rhs.len_)
    {
        data_ = new char[len_ + 1];
        std::strcpy(data_, rhs.data_);
        std::cout << "拷贝: " << data_ << "\n";
    }

    // 移动构造 可以**“偷”资源而，节约性能
    MyString(MyString &&rhs) noexcept : data_(rhs.data_), len_(rhs.len_)
    {
        rhs.data_ = nullptr;
        std::cout << "移动: " << data_ << "\n";
    }
};

template <typename T>
T &&my_move(T &t)
{
    // static_cast<T&&>。它的意思是将左值转换为右值
    return static_cast<T &&>(t);
}

int main()
{
    MyString x("hello");
    MyString a(x); //
    MyString y("hello");
    // 返回类型为右值此时触发移动构造，节约性能
    MyString b(my_move(y));
    // 标准库提供了类似my_moved的方法 std::move
    // MyString b(std::move(y));
    return 0;
}
